import axios from 'axios';

// 创建axios实例
const api = axios.create({
    baseURL: 'http://localhost:8080', // 后端API基础URL
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json'
    }
});

// 请求拦截器，添加token
api.interceptors.request.use(
    config => {
        const token = localStorage.getItem('token');
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// 响应拦截器，处理token过期等情况
api.interceptors.response.use(
    response => {
        return response.data;
    },
    error => {
        if (error.response && error.response.status === 401) {
            // token过期或未登录，跳转到登录页
            localStorage.removeItem('token');
            localStorage.removeItem('userInfo');
            window.location.href = '/login';
        }
        return Promise.reject(error);
    }
);

// 用户登录
export const login = async (username, password) => {
    try {
        const response = await api.post('/user/user/login', {
            username,
            password
        });

        // 修改这里，检查code字段而不是success字段
        if (response.code === 1 && response.data.token) {
            localStorage.setItem('token', response.data.token);
            localStorage.setItem('userInfo', JSON.stringify(response.data));
            // 单独保存用户ID到本地存储
            if (response.data.id) {
                localStorage.setItem('userId', response.data.id);
            }
        }

        return response;
    } catch (error) {
        console.error('登录失败:', error);
        throw error;
    }
};

// 用户注册
export const register = async (username, password, rePassword) => {
    try {
        const response = await api.post('/user/user/register', {
            username,
            password,
            rePassword
        });
        return response;
    } catch (error) {
        console.error('注册失败:', error);
        throw error;
    }
};

// 用户登出
export const logout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
    window.location.href = '/login';
};

// 获取当前用户信息
export const getCurrentUser = () => {
    const userInfo = localStorage.getItem('userInfo');
    return userInfo ? JSON.parse(userInfo) : null;
};

// 检查用户是否已登录
export const isLoggedIn = () => {
    return !!localStorage.getItem('token');
};

// 获取当前用户ID
export const getCurrentUserId = () => {
    // 优先从userId字段获取
    const userId = localStorage.getItem('userId');
    if (userId) {
        return userId;
    }

    // 如果没有userId字段，尝试从userInfo中获取
    try {
        const userInfo = localStorage.getItem('userInfo');
        if (userInfo) {
            const parsedUserInfo = JSON.parse(userInfo);
            if (parsedUserInfo.id) {
                // 同时保存到userId字段，以便下次直接获取
                localStorage.setItem('userId', parsedUserInfo.id);
                return parsedUserInfo.id;
            }
        }
    } catch (error) {
        console.error('解析userInfo失败:', error);
    }

    // 如果都获取不到，返回默认值1
    return '1';
};

// 提供与App.vue中调用匹配的别名函数
export const isAuthenticated = isLoggedIn;
export const getUserInfo = getCurrentUser;

// 默认导出所有函数
const authService = {
    login,
    register,
    logout,
    getCurrentUser,
    getCurrentUserId,
    isLoggedIn,
    isAuthenticated,
    getUserInfo
};

export default authService;